<template>
  <div class="role-list-container">
    <a-card class="main-card">
      <template #title>
        <div class="card-title">
          <span>角色管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-header">
        <a-form layout="inline">
          <a-form-item label="角色名称">
            <a-input
              v-model:value="searchForm.roleName"
              placeholder="请输入角色名称"
              allowClear
              @change="handleSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
            <a-button type="primary" style="margin-left: 8px" @click="showAddModal">
              新增角色
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 角色列表 -->
      <a-table
        :columns="columns"
        :data-source="roleList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" @click="handleConfigPermission(record)">配置权限</a-button>
              <a-popconfirm
                title="确定要删除该角色吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑角色弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑角色"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirmLoading="editLoading"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
      >
        <a-form-item label="角色名称" name="roleName">
          <a-input
            v-model:value="editForm.roleName"
            placeholder="请输入角色名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number
            v-model:value="editForm.sort"
            placeholder="请输入排序值"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增角色弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="新增角色"
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
      :confirmLoading="addLoading"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        layout="vertical"
      >
        <a-form-item label="角色名称" name="roleName">
          <a-input
            v-model:value="addForm.roleName"
            placeholder="请输入角色名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number
            v-model:value="addForm.sort"
            placeholder="请输入排序值"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 配置权限抽屉 -->
    <a-drawer
      title="配置权限"
      placement="right"
      :width="600"
      :visible="permissionDrawerVisible"
      @close="handlePermissionDrawerClose"
    >
      <div class="permission-drawer-content">
        <a-transfer
          :targetKeys="targetKeys"
          :dataSource="transferData"
          @change="handleTransferChange"
          :titles="['可选权限', '已选权限']"
          :listStyle="{
            width: '250px',
            height: '400px',
          }"
          :render="(item: TransferItem) => item.title"
        />
        <div class="drawer-footer">
          <a-button style="margin-right: 8px" @click="handlePermissionDrawerClose">
            取消
          </a-button>
          <a-button type="primary" :loading="permissionLoading" @click="handlePermissionSubmit">
            确定
          </a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { listRole, modifyRole, delRole, addRole, roleDetail, bindRolePermission } from '@/api/role';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

interface Role {
  id: number;
  roleName: string;
  sort: number;
}

interface Permission {
  id: number;
  permissionId: string;
  permissionName: string;
  fatherPermissionId: string;
  fatherPermissionName: string;
  sort: number;
}

// 搜索表单
const searchForm = reactive({
  roleName: '',
  pageNum: 1,
  pageSize: 10
});

// 角色列表数据
const roleList = ref<Role[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格列定义
const columns = [
  {
    title: '角色ID',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    width: 200
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 编辑相关数据
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  id: 0,
  roleName: '',
  sort: 0
});

// 编辑表单验证规则
const editFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在2-20个字符之间', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
};

// 新增相关数据
const addModalVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  roleName: '',
  sort: 0
});

// 新增表单验证规则
const addFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在2-20个字符之间', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
};

// 权限配置相关数据
const permissionDrawerVisible = ref(false);
const permissionLoading = ref(false);
const selectedPermissions = ref<string[]>([]);
const currentRoleId = ref<number>(0);
const permissionList = ref<Permission[]>([]);
const canAddPermission = ref<Permission[]>([]);

// 加载角色列表
const loadRoleList = async () => {
  loading.value = true;
  try {
    const res = await listRole(
      searchForm.pageNum,
      searchForm.pageSize,
      searchForm.roleName
    );

    if (res.data.code === 200) {
      roleList.value = res.data.data.list;
      pagination.total = res.data.data.total;
      pagination.current = res.data.data.pageNum;
      pagination.pageSize = res.data.data.pageSize;
    } else {
      message.error(res.data.msg || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    message.error('获取角色列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理表格变化（分页）
const handleTableChange = (pag: TablePaginationConfig) => {
  searchForm.pageNum = pag.current || 1;
  searchForm.pageSize = pag.pageSize || 10;
  loadRoleList();
};

// 处理搜索
const handleSearch = () => {
  searchForm.pageNum = 1;
  loadRoleList();
};

// 处理重置
const handleReset = () => {
  searchForm.roleName = '';
  searchForm.pageNum = 1;
  loadRoleList();
};

// 处理编辑
const handleEdit = (record: Role) => {
  editForm.id = record.id;
  editForm.roleName = record.roleName;
  editForm.sort = record.sort;
  editModalVisible.value = true;
};

// 提交编辑
const handleEditSubmit = () => {
  editFormRef.value?.validate().then(async () => {
    editLoading.value = true;
    try {
      const res = await modifyRole({
        roleId: editForm.id,
        roleName: editForm.roleName,
        sort: editForm.sort
      });

      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        loadRoleList();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    } catch (error) {
      console.error('修改角色失败:', error);
      message.error('修改失败，请稍后重试');
    } finally {
      editLoading.value = false;
    }
  });
};

// 取消编辑
const handleEditCancel = () => {
  editFormRef.value?.resetFields();
  editModalVisible.value = false;
};

// 处理删除
const handleDelete = async (record: Role) => {
  try {
    const res = await delRole(record.id);

    if (res.data.code === 200) {
      message.success('删除成功');
      loadRoleList();
    } else {
      message.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除角色失败:', error);
    message.error('删除失败，请稍后重试');
  }
};

// 显示新增弹窗
const showAddModal = () => {
  addModalVisible.value = true;
};

// 提交新增
const handleAddSubmit = () => {
  addFormRef.value?.validate().then(async () => {
    addLoading.value = true;
    try {
      const res = await addRole({
        roleName: addForm.roleName,
        sort: addForm.sort
      });

      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        loadRoleList();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    } catch (error) {
      console.error('添加角色失败:', error);
      message.error('添加失败，请稍后重试');
    } finally {
      addLoading.value = false;
    }
  });
};

// 取消新增
const handleAddCancel = () => {
  addFormRef.value?.resetFields();
  addModalVisible.value = false;
};

interface TransferItem {
  key: string;
  title: string;
  description: string;
}

// 配置权限按钮逻辑
const transferData = ref<TransferItem[]>([]);
const targetKeys = ref<string[]>([]);

const handleConfigPermission = async (record: Role) => {
  // 先打开抽屉
  permissionDrawerVisible.value = true;
  currentRoleId.value = record.id;
  permissionLoading.value = true;
  
  try {
    const res = await roleDetail(record.id);
    if (res.data.code === 200) {
      const { permissionList, canAddPermission } = res.data.data;

      // 右侧数据
      const rightData: TransferItem[] = [];
      const rightKeys: string[] = [];
      if(permissionList && permissionList.length > 0) {
        permissionList.forEach((param: Permission) => {
          rightData.push({
            key: param.permissionId,
            title: param.permissionName,
            description: param.fatherPermissionName
          });
          rightKeys.push(param.permissionId);
        });
      }

      // 左侧数据
      const leftData: TransferItem[] = [];
      if(canAddPermission && canAddPermission.length > 0) {
        canAddPermission.forEach((param: Permission) => {
          leftData.push({
            key: param.permissionId,
            title: param.permissionName,
            description: param.fatherPermissionName
          });
        });
      }

      // 合并左右数据
      transferData.value = [...leftData, ...rightData];
      targetKeys.value = rightKeys;
    } else {
      message.error(res.data.msg || '获取权限数据失败');
    }
  } catch (error) {
    console.error('获取权限数据失败:', error);
    message.error('获取权限数据失败，请稍后重试');
  } finally {
    permissionLoading.value = false;
  }
};

// 处理穿梭框变化
const handleTransferChange = (newTargetKeys: string[]) => {
  targetKeys.value = newTargetKeys;
};

// 关闭权限配置抽屉
const handlePermissionDrawerClose = () => {
  permissionDrawerVisible.value = false;
  selectedPermissions.value = [];
  currentRoleId.value = 0;
  permissionList.value = [];
  canAddPermission.value = [];
};

// 提交权限配置
const handlePermissionSubmit = async () => {
  permissionLoading.value = true;
  try {
    const res = await bindRolePermission({
      roleId: currentRoleId.value,
      permissionIdList: targetKeys.value
    });

    if (res.data.code === 200) {
      message.success('权限配置成功');
      permissionDrawerVisible.value = false;
      loadRoleList(); // 刷新角色列表
    } else {
      message.error(res.data.msg || '权限配置失败');
    }
  } catch (error) {
    console.error('保存权限配置失败:', error);
    message.error('保存失败，请稍后重试');
  } finally {
    permissionLoading.value = false;
  }
};

// 页面加载时获取角色列表
onMounted(() => {
  loadRoleList();
});
</script>

<style scoped>
.role-list-container {
  padding: 24px;
}

.main-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.search-header {
  margin-bottom: 24px;
}

.action-header {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-btn-link) {
  padding: 4px 8px;
}

.permission-drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
}
</style>
